package net.sppan.blog.controller;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

import net.sppan.blog.bean.OfferRequestBean;
import net.sppan.blog.bean.URLParam;
import net.sppan.blog.model.Offer;
import net.sppan.blog.store.UserStore;
import net.sppan.blog.utils.AESUtil;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.plugin.activerecord.Record;

@Before(SessionInViewInterceptor.class)
public class BaseController extends Controller {

	/**
	 * 返回ajax请求结果以及相应信息
	 * @param isSuccess
	 * @param msg
	 */
	public void renderJson(boolean isSuccess, String msg) {
		Record record = new Record();
		record.set("isSuccess", isSuccess);
		record.set("msg", msg);
		super.renderJson(record);
	}

	/**
	 * 取Request中的数据对象
	 * @param valueType
	 * @return
	 * @throws Exception 
	 */
	protected <T> T getRequestObject(Class<T> valueType) throws Exception {
		StringBuilder json = new StringBuilder();
		BufferedReader reader = this.getRequest().getReader();
		String line = null;
		while ((line = reader.readLine()) != null) {
			json.append(line);
		}
		reader.close();
		String str = AESUtil.desEncrypt(json.toString());
		return JSONObject.parseObject(str, valueType);
	}

	protected String buildClickUrl(OfferRequestBean requestBean, Offer o) {
		Map<URLParam, String> tmap = new HashMap<>();
		tmap.put(URLParam.tid, requestBean.getTid());
		tmap.put(URLParam.userId, requestBean.getUserID());
		tmap.put(URLParam.userName, UserStore.instance.getUserName(requestBean.getUserID()));
		String parentId = UserStore.instance.getParentId(requestBean.getUserID());
		tmap.put(URLParam.parentId, parentId);
		tmap.put(URLParam.parentName, UserStore.instance.getUserName(parentId));
		tmap.put(URLParam.price, o.getPrice());
		tmap.put(URLParam.offerId, o.getId().toString());
		tmap.put(URLParam.hardwareID, requestBean.getHardwareID());

		StringBuilder paramUrl = new StringBuilder();
		for (URLParam param : URLParam.values()) {
			String k = param.getCode();
			paramUrl.append(k).append("=").append(tmap.get(param)).append("&");
		}
		String s = paramUrl.toString();
		if (s.endsWith("&")) {
			s = s.substring(0, s.length() - 1);
		}
		return s;
	}

}
